<template>
	<view class="order-list">
		<!-- 状态切换栏 -->
		<scroll-view scroll-x class="status-bar" :show-scrollbar="false">
			<view class="status-item" v-for="(item, index) in statusList" :key="index"
				:class="{ active: currentStatus === item.value }" @tap="switchStatus(item.value)">
				<text>{{ item.label }}</text>
			</view>
		</scroll-view>

		<!-- 订单列表 -->
		<scroll-view scroll-y class="order-scroll" @scrolltolower="loadMore" :refresher-enabled="true"
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh">
			<view class="order-item" v-for="order in orderList" :key="order.id" @tap="goToDetail(order.id)">
				<!-- 订单头部 -->
				<view class="order-header">
					<text class="venue-name">{{ order.venueName }}</text>
					<text class="order-status" :class="{
						'success': order.orderStatus === 'SUCCESS',
						'refund': order.orderStatus === 'REFUND',
						'notpay': order.orderStatus === 'NOTPAY',
						'closed': order.orderStatus === 'CLOSED',
						'revoked': order.orderStatus === 'REVOKED',
						'userpaying': order.orderStatus === 'USERPAYING',
						'payerror': order.orderStatus === 'PAYERROR'
					}">
						{{ getStatusText(order.orderStatus) }}
					</text>
				</view>

				<!-- 订单内容 -->
				<view class="order-content">
					<view class="order-info">
						<text class="date">预订日期：{{ formatDate(order.orderDate) }}</text>
						<view class="items">
							<text class="item" v-for="(item, index) in order.orderItems" :key="index">
								{{ item.venueSpecName }} {{ item.timeSlot }}
							</text>
						</view>
					</view>
					<view class="price-info">
						<text class="price">¥{{ order.totalAmount }}</text>
					</view>
				</view>

				<!-- 订单底部 -->
				<view class="order-footer">
					<text class="order-time">下单时间：{{ order.createTime }}</text>
					<view class="order-actions">
						<button type="primary" size="mini" class="action-btn" v-if="order.orderStatus === 'NOTPAY'"
							style="transform: scale(0.8); margin: 0 -10rpx;" @tap.stop="handlePay(order)">继续支付</button>
						<button type="primary" size="mini" class="action-btn cancel-btn"
							v-if="order.orderStatus==='NOTPAY'" style="transform: scale(0.8); margin: 0 -10rpx;"
							@tap.stop="cancelOrder(order)">取消订单</button>
						<button type="primary" size="mini" class="action-btn cancel-btn"
							v-if="order.orderStatus === 'SUCCESS'" style="transform: scale(0.8); margin: 0 -10rpx;"
							@tap.stop="applyRefund(order)">申请退款</button>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="orderList.length === 0">
				<image src="/static/images/empty-order.png" mode="aspectFit"></image>
				<text>暂无相关订单</text>
			</view>

			<!-- 加载更多 -->
			<view class="loading-more" v-if="orderList.length > 0">
				<text v-if="hasMore">加载中...</text>
				<text v-else>没有更多了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		listOrder,
		goOnPay,
		cancelOrder,
		applyRefund
	} from '@/api/order/order.js'

	import {
		getConfigKey
	} from '../../api/system/config'

	export default {
		data() {
			return {
				statusList: [{
					label: '全部',
					value: ''
				}, {
					label: '待支付',
					value: 'NOTPAY'
				}, {
					label: '支付中',
					value: 'USERPAYING'
				}, {
					label: '已支付',
					value: 'SUCCESS'
				}, {
					label: '已退款',
					value: 'REFUND'
				}, {
					label: '已关闭',
					value: 'CLOSED'
				}],
				currentStatus: '',
				orderList: [],
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					orderStatus: ''
				},
				hasMore: true,
				refreshing: false,
				serviceRate: 0
			}
		},

		onLoad() {
			this.getOrderList()
			this.getConfigKey()
		},

		methods: {
			//获取退款服务费率
			getConfigKey() {
				getConfigKey('sys.withdraw.service.rate').then(res => {
					console.log('getConfigKey', res)
					this.serviceRate = Number(res.data)
				})
			},
			// 切换状态
			switchStatus(status) {
				this.currentStatus = status
				this.queryParams.orderStatus = status
				this.queryParams.pageNum = 1
				this.orderList = []
				this.hasMore = true
				this.getOrderList()
			},

			// 获取订单列表
			async getOrderList() {
				try {
					const res = await listOrder(this.queryParams)
					console.log('listOrder', res)
					if (res.code === 200) {
						const {
							rows,
							total
						} = res
						if (this.queryParams.pageNum === 1) {
							this.orderList = rows
						} else {
							this.orderList = [...this.orderList, ...rows]
						}
						this.hasMore = this.orderList.length < total
					}
				} catch (error) {
					console.error('获取订单列表失败:', error)
					uni.showToast({
						title: '获取订单列表失败',
						icon: 'none'
					})
				}
			},

			// 加载更多
			loadMore() {
				if (!this.hasMore) return
				this.queryParams.pageNum++
				this.getOrderList()
			},

			// 下拉刷新
			async onRefresh() {
				this.refreshing = true
				this.queryParams.pageNum = 1
				await this.getOrderList()
				this.refreshing = false
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'SUCCESS': '支付成功',
					'REFUND': '已退款',
					'NOTPAY': '未支付',
					'CLOSED': '已关闭',
					'REVOKED': '已撤销',
					'USERPAYING': '支付中',
					'PAYERROR': '支付失败'
				}
				return statusMap[status] || '未知状态'
			},

			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '--'
				return dateStr.split(' ')[0]
			},

			// 跳转到详情页
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${id}`
				})
			},

			// 继续支付
			async handlePay(order) {
				try {
					const res = await goOnPay({
						id: order.id
					})
					console.log(res)
					if (res.code === 200) {
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: res.data.timeStamp,
							nonceStr: res.data.nonceStr,
							package: res.data.packageValue,
							signType: res.data.signType,
							paySign: res.data.paySign,
							success: () => {
								uni.redirectTo({
									url: `/pages/order/result?orderId=${order.id}&amount=${order.totalAmount}`
								})
							},
							fail: (err) => {
								console.error('支付失败:', err)
								uni.showToast({
									title: '支付失败',
									icon: 'none'
								})
							}
						})
					}
				} catch (error) {
					console.error('发起支付失败:', error)
					uni.showToast({
						title: '发起支付失败',
						icon: 'none'
					})
				}
			},

			// 取消订单
			async cancelOrder(order) {
				try {
					uni.showModal({
						title: '提示',
						content: '确定取消订单？',
						success: async (res) => {
							if (res.confirm) {
								const response = await cancelOrder(order.id)
								if (response.code === 200) {
									uni.showToast({
										title: '订单已取消',
										icon: 'success'
									})
									// 刷新订单列表
									this.refreshOrders()
								}
							}
						}
					})
				} catch (error) {
					console.error('取消订单失败:', error)
					uni.showToast({
						title: '取消失败',
						icon: 'none'
					})
				}
			},

			// 申请退款
			async applyRefund(order) {
				try {
					uni.showModal({
						title: '申请退款',
						content: `确定申请退款该订单？取消将收取${this.serviceRate}%的手续费补偿球场`,
						success: async (res) => {
							if (res.confirm) {
								const response = await applyRefund(order.id)
								if (response.code === 200) {
									uni.showToast({
										title: '退款申请已提交',
										icon: 'success'
									})
									// 刷新订单列表
									this.refreshOrders()
								}
							}
						}
					})
				} catch (error) {
					console.error('申请退款失败:', error)
					uni.showToast({
						title: '申请失败',
						icon: 'none'
					})
				}
			},

			// 刷新订单列表
			refreshOrders() {
				this.pageNum = 1
				this.getOrderList(true)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-list {
		min-height: 100vh;
		background: #f5f5f5;

		.status-bar {
			background: #fff;
			white-space: nowrap;
			padding: 20rpx 0;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 1;

			.status-item {
				display: inline-block;
				padding: 0 30rpx;
				font-size: 28rpx;
				color: #666;
				position: relative;

				&.active {
					color: #ff6b35;
					font-weight: bold;

					&::after {
						content: '';
						position: absolute;
						left: 50%;
						bottom: -10rpx;
						transform: translateX(-50%);
						width: 40rpx;
						height: 4rpx;
						background: #ff6b35;
						border-radius: 2rpx;
					}
				}
			}
		}

		.order-scroll {
			height: calc(100vh - 88rpx);
			margin-top: 88rpx;
			padding: 20rpx;
			box-sizing: border-box;
		}

		.order-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.order-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;

				.venue-name {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}

				.order-status {
					font-size: 28rpx;

					&.success {
						color: #4CAF50;
					}

					&.notpay {
						color: #ff6b35;
					}

					&.userpaying {
						color: #2196F3;
					}

					&.refund {
						color: #9C27B0;
					}

					&.closed {
						color: #999;
					}

					&.revoked {
						color: #999;
					}

					&.payerror {
						color: #F44336;
					}
				}
			}

			.order-content {
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee;

				.order-info {
					flex: 1;
					margin-right: 20rpx;

					.date {
						font-size: 26rpx;
						color: #666;
						margin-bottom: 10rpx;
					}

					.items {
						display: flex;
						flex-direction: column;
						gap: 8rpx;

						.item {
							font-size: 28rpx;
							color: #333;
						}
					}
				}

				.price-info {
					.price {
						font-size: 36rpx;
						color: #ff6b35;
						font-weight: bold;
					}
				}
			}

			.order-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-top: 20rpx;

				.order-time {
					font-size: 24rpx;
					color: #999;
				}

				.action-btn {
					font-size: 24rpx;
					padding: 6rpx 20rpx;
					border-radius: 30rpx;
					margin: 0;

					// 继续支付按钮样式
					&[type="primary"] {
						color: #fff;
						background: #4CAF50;
						border: none;
					}

					// 取消订单和申请退款按钮样式
					&.cancel-btn {
						color: #666;
						background: #f5f5f5;
						border: 1px solid #ddd;
					}

					&:active {
						opacity: 0.8;
					}
				}
			}
		}

		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 100rpx 0;

			image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 20rpx;
			}

			text {
				font-size: 28rpx;
				color: #999;
			}
		}

		.loading-more {
			text-align: center;
			padding: 20rpx 0;
			font-size: 24rpx;
			color: #999;
		}
	}

	.order-actions {
		display: flex;
		justify-content: flex-end;
		padding: 20rpx;
		gap: 10rpx;

		.action-btn {
			padding: 6rpx 20rpx;
			font-size: 26rpx;
			border-radius: 30rpx;

			// 继续支付按钮样式
			&[type="primary"] {
				color: #fff;
				background: #4CAF50;
				border: none;
			}

			// 取消订单和申请退款按钮样式
			&.cancel-btn {
				color: #666;
				background: #f5f5f5;
				border: 1px solid #ddd;
			}
		}
	}
</style>